package com.qf.controller;

import cn.dsna.util.images.ValidateCode;
import com.qf.entity.Address;
import com.qf.entity.User;
import com.qf.service.AddressService;
import com.qf.service.UserService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.RandomUtils;
import com.qf.utils.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Base64;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author wgy
 * @version V1.0
 * @project gp12_xiaomi
 * @package ${PACKAGE_NAME}
 * @description: ${TODO}
 * @date 2022/6/22 11:00
 */
@WebServlet(name = "UserServlet",urlPatterns = "/userservlet")
public class UserServlet extends BaseServlet {

    //注册功能
    public String register(HttpServletRequest request,HttpServletResponse response){
        //1接受数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        //2校验
        //先把数据放入域中
        request.setAttribute("username",username);
        request.setAttribute("password",password);
        request.setAttribute("repassword",repassword);
        request.setAttribute("email",email);
        request.setAttribute("gender",gender);
        //2.1非空校验
        if(StringUtils.isEmpty(username)){
            request.setAttribute("registerMsg","用户不能为空");
            return "/register.jsp";
        }
        if(StringUtils.isEmpty(password)){
            request.setAttribute("registerMsg","密码不能为空");
            return "/register.jsp";
        }
        if(!password.equals(repassword)){
            request.setAttribute("registerMsg","两次密码不一致");
            return "/register.jsp";
        }
        if(StringUtils.isEmpty(email)){
            request.setAttribute("registerMsg","邮箱不能为空");
            return "/register.jsp";
        }
        if(StringUtils.isEmpty(gender)){
            request.setAttribute("registerMsg","性别不能为空");
            return "/register.jsp";
        }
        //邮箱格式的校验
        String reg="^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        if(!Pattern.matches(reg, email)){
            request.setAttribute("registerMsg","邮箱格式不正确");
            return "/register.jsp";
        }
        //3创建业务对象
        UserService userService=new UserServiceImpl();
        //4调用业务方法
        //flag:0没有激活  1表示激活  2 失效
        //role: 0管理员 1普通用户
        //code:激活码
        User user=new User(0, username, password, email, gender, 0, 1, RandomUtils.createActiveCode());
        try {
            userService.regist(user);
            return "redirect:/registerSuccess.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("registerMsg", "注册失败:"+e.getMessage());
        }
        return "/index.jsp";//转发
    }
    //登录功能
    public String login(HttpServletRequest request,HttpServletResponse response){
        //1接收数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");
        String auto = request.getParameter("auto");
        //2校验
        //2.1非空校验
        if(StringUtils.isEmpty(username)){
            request.setAttribute("msg","用户不能为空" );
            return "/login.jsp";
        }
        if(StringUtils.isEmpty(password)){
            request.setAttribute("msg","密码为空" );
            return "/login.jsp";
        }
        if(StringUtils.isEmpty(vcode)){
            request.setAttribute("msg","验证码为空" );
            return "/login.jsp";
        }
        //2.2验证码是否正确
        String code = (String) request.getSession().getAttribute("code");
        if(!vcode.equalsIgnoreCase(code)){
            request.setAttribute("msg","验证码输入有误" );
            return "/login.jsp";
        }
        //3创建业务对象
        UserService userService=new UserServiceImpl();
        //4调用方法
        try {
            User user=userService.login(username,password);
            request.getSession().setAttribute("user", user);
            //判断是否勾选自动登录
            if(auto!=null) {
                String userinfo = username + "#" + password;
                //使用Base64编码[加密]
                userinfo = Base64.getEncoder().encodeToString(userinfo.getBytes("utf-8"));
                Cookie cookie = new Cookie("userinfo", userinfo);
                //设置参数
                cookie.setPath(request.getContextPath());
                //设置有效期
                cookie.setMaxAge(60 * 60 * 24 * 14);
                //设置httponly
                cookie.setHttpOnly(true);
                response.addCookie(cookie);
            }
            return "redirect:/index.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","登录失败:"+e.getMessage());
            return "/login.jsp";
        }
    }
    //检查用户名是否存在
    public String checkUserName(HttpServletRequest request,HttpServletResponse response) throws Exception{
        String username = request.getParameter("username");
        response.setContentType("text/html;charset=utf-8");
        System.out.println("username:"+username);
        //1校验
        if(StringUtils.isEmpty(username)){
            return null;
        }
        //2创建业务对象
        UserService userService=new UserServiceImpl();
        try {
            //3调用方法
            boolean b=userService.selectByUserName(username);
            //4返回内容
            if(b){
                response.getWriter().write("1");
            }else{
                response.getWriter().write("0");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //返回验证码
    public String code(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //创建验证码对象
        ValidateCode validateCode=new ValidateCode(120,30 ,4 , 20);
        //获取验证码
        String code = validateCode.getCode();
        //放入session
        request.getSession().setAttribute("code", code);
        //返回验证码
        validateCode.write(response.getOutputStream());

        return null;
    }
    //退出
    public String logOut(HttpServletRequest request,HttpServletResponse response) throws Exception{
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        session.invalidate();
        Cookie cookie=new Cookie("userinfo", "");
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/index.jsp";
    }

    //----------地址管理的方法-------------

    //获取地址信息
    public String getAddress(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //1判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/index.jsp";
        }
        //2创建业务对象
        AddressService addressService=new AddressServiceImpl();
        try {
            //3调用方法
            List<Address> addList = addressService.findByUid(user.getId());
            //4放入域中
            request.setAttribute("addList",addList);
            //5转发
            return "/self_info.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","获取收货地址失败:"+e.getMessage());
            return "/message.jsp";
        }
    }

    //添加收货地址
    public String addAddress(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //1判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/index.jsp";
        }
        //2接收数据
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        //3校验
        if(StringUtils.isEmpty(name)){
            request.setAttribute("msg","姓名不能为空" );
            return "/self_info.jsp";
        }
        if(StringUtils.isEmpty(phone)){
            request.setAttribute("msg","电话不能为空" );
            return "/self_info.jsp";
        }
        if(StringUtils.isEmpty(detail)){
            request.setAttribute("msg","地址不能为空" );
            return "/self_info.jsp";
        }
        //4创建业务对象
        AddressService addressService=new AddressServiceImpl();
        //5调用方法
        try {
            Address address=new Address(0, detail, name, phone, user.getId(), 0);
            addressService.add(address);
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","添加地址失败:"+e.getMessage());
            return "/self_info.jsp";
        }

    }

    //删除

    public String deleteAddress(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //1判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/index.jsp";
        }
        //2获取参数
        String id = request.getParameter("id");
        //3校验
        if(StringUtils.isEmpty(id)){
            request.setAttribute("msg","删除失败");
            return "/message.jsp";
        }
        //4创建业务对象
        AddressService  addressService=new AddressServiceImpl();
        //5调用方法
        try {
            addressService.delete(Integer.parseInt(id));
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","删除失败,地址已经被使用");
            return "/message.jsp";
        }

    }

    //修改地址
    public String updateAddress(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //1判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/index.jsp";
        }
        //2接收数据
        String id = request.getParameter("id");
        String level = request.getParameter("level");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        //3校验
        if(StringUtils.isEmpty(id)){
            request.setAttribute("msg","地址编号不能为空" );
            return "/message.jsp";
        }
        if(StringUtils.isEmpty(level)){
            request.setAttribute("msg","级别不能为空" );
            return "/message.jsp";
        }
        if(StringUtils.isEmpty(name)){
            request.setAttribute("msg","收货人不能为空" );
            return "/message.jsp";
        }
        if(StringUtils.isEmpty(phone)){
            request.setAttribute("msg","电话不能为空" );
            return "/message.jsp";
        }if(StringUtils.isEmpty(detail)){
            request.setAttribute("msg","详细地址不能为空" );
            return "/message.jsp";
        }
        //4创建业务对象
        AddressService addressService=new AddressServiceImpl();
        //5调用方法
        try {
            Address address=new Address(Integer.parseInt(id), detail, name, phone, user.getId(),Integer.parseInt(level) );
            addressService.update(address);
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","修改地址失败:"+e.getMessage() );
            return "/message.jsp";
        }
    }

    //设置默认地址

    public String defaultAddress(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //1判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/index.jsp";
        }
        //2接收id
        String id = request.getParameter("id");
        //3校验
        if(StringUtils.isEmpty(id)){
            request.setAttribute("msg","地址编号不能为空" );
            return "/message.jsp";
        }
        //4创建业务对象
        AddressService addressService=new AddressServiceImpl();
        //5调用放阿飞
        try {
            addressService.updateLevel(Integer.parseInt(id),user.getId());
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","修改默认地址失败:"+e.getMessage() );
            return "/message.jsp";
        }
    }
}
